<?php
header("Content-type:text/html;charset=utf-8");

	/**
     * 字符是否存在字符串中
     * @author xuan
     * @param a 字符
     * @param b 以逗号隔开的字符串，例：'1,2,3'
     */
	function inString($a,$b){
		if($b){
            $type_arr = explode(',', $b);
            return in_array($a, $type_arr);
        }
        return false;
	}

    /**
     * 生成N位数编号
     * @author xuan
     * @param a 数字
     * @param n 生成n位编号
     */
    function formatNO ($a,$n) {
        $no = pow(10,$n);
        $no += $a;
        $no = substr($no, 1);
        return $no;
    }

    /**
     * 上传文件
     * @author xuan
     * @param filearr 文件数组（若是单传，则传入一维数组，例$_FILES['key']）
     * @param filetype 文件类型（1文件 2图片 3音频 4视频 5pdf）默认图片上传
     * @param filenum 文件上传方式（1单传 2多传）默认单传
     * @param maxSize 文件大小（M）
     * @return array 文件信息
     */
    function upload($filearr='',$filetype='2',$filenum='1',$maxSize='10'){
        // 实例化上传类
        $upload = new \Think\Upload();
        // 设置附件上传大小(3M 1024*1024*3)
        $upload->maxSize   =   $maxSize * 1024 * 1024 ;
        $exts_arr = array();
        $savepath = '';
        switch ($filetype) {
            case '1':   //文件
                $exts_arr = array('jpg', 'gif', 'png', 'jpeg' ,'csv' , 'xls' , 'xlsx' , 'pdf' , 'txt' , 'mp3' ,'mp4' , 'flv' , 'html');
                $savepath = 'file';
                break;
            case '2':   //图片
                $exts_arr = array('jpg', 'gif', 'png', 'jpeg');
                $savepath = 'image';
                break;
            case '3':   //音频
                $exts_arr = array('mp3');
                $savepath = 'audio';
                break;
            case '4':   //视频
                $exts_arr = array('mp4', 'flv');
                $savepath = 'video';
                break;
            case '5':   //PDF
                $exts_arr = array('pdf');
                $savepath = 'pdf';
                break;
            case '6':   //excel
                $exts_arr = array('xls', 'xlsx' ,'csv');
                $savepath = 'excel';
                break;
            default:    //默认图片
                $exts_arr = array('jpg', 'gif', 'png', 'jpeg');
                $savepath = 'image';
                break;
        }
        // 设置附件上传类型
        $upload->exts      =   $exts_arr;
        // 设置附件上传目录
        $upload->rootPath  =   'Upload/';
        // 设置附件上传目录
        $upload->savePath  =   $savepath.'/';
        //设置附件名称
        $upload->saveName  =   array('uniqid','');
        //自动使用子目录保存上传文件 默认为true
        $upload->autoSub   =   true;
        //子目录创建方式，采用数组或者字符串方式定义
        $upload->subName   =   date('Ym').'/'.date('d');
        // 上传文件
        switch ($filenum) {
            case '1':   //单传
                $info = $upload->uploadOne($filearr);
                break;
            case '2':   //多传
                $info = $upload->upload();
                break;
            default:    //默认单传
                $info = $upload->uploadOne($filearr);
                break;
        }
        $result = array();
        if(!$info) {// 上传错误提示错误信息
            $result['status'] = 0;
            $result['msg'] = $upload->getError();
            $result['data'] = array();
        }else{// 上传成功
            $result['status'] = 1;
            $result['msg'] = '上传成功！';
            $result['data'] = $info;
            $result['filepath'] = C(DOCUMENT_UPLOAD).$info['savepath'].$info['savename'];
        }
        return $result;
    }

    /**
     * 创建文件夹
     * @author xuan
     * @param dir 文件夹名
     */
    function create_folders($dir){
        return is_dir($dir) or (create_folders(dirname($dir)) and mkdir($dir, 0777));
    }

    function getpage($count, $pagesize = 1) {
        $p = new Think\Page($count, $pagesize);
        $p->setConfig('header', ' <li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
        $p->setConfig('prev', '上一页');
        $p->setConfig('next', '下一页');
        $p->setConfig('last', '末页');
        $p->setConfig('first', '首页');
        $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
        $p->lastSuffix = false;//最后一页不显示为总页数
        return $p;
    }

    /**
     * 获取选项编号
     * @author xuan
     * @param value 值(数字1-9)
     */
    function getExamOption($value){
        $arr = array('-请选择-','①','②','③','④','⑤','⑥','⑦','⑧','⑨');
        return $arr[$value];
    }

    /**
     * 系统截取字符串，如果超出用。。。代替
     * @author xuan
     */
    function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
        if(function_exists("mb_substr")){
            if($suffix)
            return mb_substr($str, $start, $length, $charset)."...";
            else
            return mb_substr($str, $start, $length, $charset);
        }elseif(function_exists('iconv_substr')) {
            if($suffix)
            return iconv_substr($str,$start,$length,$charset)."...";
            else
            return iconv_substr($str,$start,$length,$charset);
        }
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
        if($suffix) return $slice."…";
        return $slice;
    }

    /**
     * 相乘，供模板使用
     * @author xuan
     * @param  $a
     * @param  $b
     */
    function template_multiply($a,$b){
        echo($a * $b);
    }

    /**
     * 计算两个坐标的直线距离
     * @author xuan
     * @param  $lat1 纬度1
     * @param  $lng1 经度1
     * @param  $lat2 纬度2
     * @param  $lng2 经度2
     */
    function getDistance ($lat1, $lng1, $lat2, $lng2) {
        $earthRadius = 6378138; //近似地球半径米
        // 转换为弧度
        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;
        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;
        //使用半正矢公式  用尺规来计算
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }
    /**
     * 数组分页函数 核心函数 array_slice
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
     * $count  每页多少条数据
     * $page  当前第几页
     * $array  查询出来的所有数组
     * order 0 - 不变   1- 反序
     */
    function page_array($page,$count,$array,$order){
        $page = (empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start = ($page - 1) * $count; #计算每次分页的开始位置
        if($order == 1){
            $array = array_reverse($array);
        }
        $totals = count($array);
        $pagedata = array();
        $pagedata = array_slice($array,$start,$count);
        return $pagedata; #返回查询数据
    }

    /**
    * 数组转xls格式的excel文件
    * @param  array  $data      需要生成excel文件的数组
    * @param  string $filename  生成的excel文件名
    *      示例数据：
    *       $data = array(
    *          array(NULL, 2010, 2011, 2012),
    *           array('Q1',   12,   15,   21),
    *           array('Q2',   56,   73,   86),
    *           array('Q3',   52,   61,   69),
    *           array('Q4',   30,   32,    0),
    *          );
    */
    function create_xls($data,$filename='simple.xls'){
        ini_set('max_execution_time', '0');
        Vendor('PHPExcel.PHPExcel');
        $filename=str_replace('.xls', '', $filename).'.xls';
        $phpexcel = new PHPExcel();
        $phpexcel->getProperties()
            ->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $phpexcel->getActiveSheet()->fromArray($data);
        $phpexcel->getActiveSheet()->setTitle('Sheet1');
        $phpexcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=$filename");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $objwriter->save('php://output');
        exit;
    }

    /**
     * 导入excel文件
     * @param  string $file excel文件路径
     * @param  index  从表格第几行开始取（默认从第二行）
     * @return array        excel文件内容数组
     */
    function import_excel($file,$index = 2){
        // 判断文件是什么格式
        $type = pathinfo($file);
        $type = strtolower($type["extension"]);
        if ($type=='xlsx') {
            $type='Excel2007';
        }elseif($type=='xls' || $type=='csv') {
            $type = 'Excel5';
        }else{
            return 'wrongfile';
        }
        ini_set('max_execution_time', '0');
        Vendor('PHPExcel.PHPExcel');
        // 判断使用哪种格式
        $objReader = \PHPExcel_IOFactory::createReader($type);
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        // 取得总行数
        $highestRow = $sheet->getHighestRow();
        // 取得总列数
        $highestColumn = $sheet->getHighestColumn();
        //循环读取excel文件,读取一条,插入一条
        $data=array();
        //从第一行开始读取数据
        for($j=$index;$j<=$highestRow;$j++){
            //从A列读取数据
            for($k='A';$k<=$highestColumn;$k++){
                //读取单元格
                if($k=='F' || $k=='I'){//指定H列为时间所在列
                   $data[$j][] = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()));
                }else{
                   $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
                }
                // 读取单元格
                // $data[$j][]=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
            }
        }
        return $data;
    }

    /**
     * 微信扫码支付
     * @param  array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单金额)、out_trade_no(订单号)、product_id(产品id)
     */
    function weixinpay($order){
        $order['trade_type']='NATIVE';
        Vendor('Weixinpay.Weixinpay');
        $weixinpay=new \Weixinpay();
        $weixinpay->pay($order);
    }

    /**
     * 生成二维码
     * @param  string  $url  url连接
     * @param  integer $size 尺寸 纯数字
     * @param  string  $qr   定义不带logo二维码文件的生成路径
     * @param  string  $errorCorrectionLevel 定义容错等级 (L M Q H)从低到高
     */
    function qrcode($url,$size=10,$qr=false,$errorCorrectionLevel='L'){
        Vendor('Phpqrcode.phpqrcode');
        QRcode::png($url,$qr,$errorCorrectionLevel,$size,2,false,0xFFFFFF,0x000000);
    }

    /**
     * 跳向支付宝付款
     * @param  array $order 订单数据 必须包含 out_trade_no(订单号)、price(订单金额)、subject(商品名称标题)
     */
    function alipay($order){
        vendor('Alipay.AlipaySubmit','','.class.php');
        // 获取配置
        $config=C('ALIPAY_CONFIG');
        $data=array(
            "_input_charset" => $config['input_charset'], // 编码格式
            "logistics_fee" => "0.00", // 物流费用
            "logistics_payment" => "SELLER_PAY", // 物流支付方式SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
            "logistics_type" => "EXPRESS", // 物流类型EXPRESS（快递）、POST（平邮）、EMS（EMS）
            "notify_url" => $config['notify_url'], // 异步接收支付状态通知的链接
            "out_trade_no" => $order['out_trade_no'], // 订单号
            "partner" => $config['partner'], // partner 从支付宝商户版个人中心获取
            "payment_type" => "1", // 支付类型对应请求时的 payment_type 参数,原样返回。固定设置为1即可
            "price" => $order['price'], // 订单价格单位为元
            // "price" => 0.01, // // 调价用于测试
            "quantity" => "1", // price、quantity 能代替 total_fee。 即存在 total_fee,就不能存在 price 和 quantity;存在 price、quantity, 就不能存在 total_fee。 （没绕明白；好吧；那无视这个参数即可）
            "receive_address" => '1', // 收货人地址 即时到账方式无视此参数即可
            "receive_mobile" => '1', // 收货人手机号码 即时到账方式无视即可
            "receive_name" => '1', // 收货人姓名 即时到账方式无视即可
            "receive_zip" => '1', // 收货人邮编 即时到账方式无视即可
            "return_url" => $config['return_url'], // 页面跳转 同步通知 页面路径 支付宝处理完请求后,当前页面自 动跳转到商户网站里指定页面的 http 路径。
            "seller_email" => $config['seller_email'], // email 从支付宝商户版个人中心获取
            "service" => "create_direct_pay_by_user", // 接口名称 固定设置为create_direct_pay_by_user
            "show_url" => $config['show_url'], // 商品展示网址,收银台页面上,商品展示的超链接。
            "subject" => $order['subject'] // 商品名称商品的标题/交易标题/订单标 题/订单关键字等
        );
        $alipay=new \AlipaySubmit($config);
        $new=$alipay->buildRequestPara($data);
        $go_pay=$alipay->buildRequestForm($new, 'get','支付');
        echo $go_pay;
    }

    /**
     * 使用curl获取远程数据
     * @param  string $url url连接
     * @return string      获取到的数据
     */
    function curl_get_contents($url){
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
        // curl_setopt($ch,CURLOPT_HEADER,1);               //是否显示头部信息
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);               //设置超时
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']);        //设置 referer
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);          //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
        $r=curl_exec($ch);
        curl_close($ch);
        return $r;
    }

    // 设置验证码
    function show_verify($config=''){
        $config = '';
        if($config==''){
            $config=array(
                'codeSet'=>'1234567890',
                'fontSize'=>15,
                'useCurve'=>false,
                'imageH'=>35,
                'imageW'=>120,
                'length'=>4,
                'fontttf'=>'4.ttf',
                );
        }
        ob_clean();
        $verify = new \Think\Verify($config);
        return $verify->entry();
    }

    // 检测验证码
    function check_verify($code){
        $verify=new \Think\Verify();
        return $verify->check($code);
    }

    //极光推送
    function push($receiver_value='',$content='',$jpush_type=array(),$type='-1',$id='-1',$time='600'){
        import("Org.Util.Jpush");
        $pushObj = new \Jpush($jpush_type['app_key'],$jpush_type['master_secret'],$jpush_type['url']);
        $result = $pushObj->push($receiver_value,$content,$type,$id,$time);
        $result_arr = json_decode($result,TRUE);
        return $result_arr;
    }

    //创建32位不重复序列码
    function createRandom() {
        static $guid = '';
        $uid = uniqid("", true);
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['LOCAL_ADDR'];
        $data .= $_SERVER['LOCAL_PORT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        $guid = substr($hash,  0,  8) .
                substr($hash,  8,  4) .
                substr($hash, 12,  4) .
                substr($hash, 16,  4) .
                substr($hash, 20, 12);
        return $guid;
    }

    //创建16位不重复订单号
    function createOrdernum() {
        $ordernum = (time()-123456789).sprintf('%06d', rand(0, 999999));
        return $ordernum;
    }



    //阿里大鱼短信验证码
    function alidayucode($code,$phonenums){
        Vendor('Alidayu.TopSdk');
        $config=C('ALIDAYU_CONFIG');
        $c = new TopClient;
        $c->appkey = $config['appkey'];
        $c->secretKey = $config['secretKey'];
        $req = new AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend($config['extend']);
        $req->setSmsType($config['smsType']);
        $req->setSmsFreeSignName($config['smsFreeSignName']);
        $req->setSmsParam("{\"code\":\"".$code."\",\"product\":\"迷笛考级\"}");
        $req->setRecNum($phonenums);
        $req->setSmsTemplateCode($config['smsTemplateCode']);
        $resp = $c->execute($req);
        return $resp;
    }



    //阿里大鱼短信通知
    function alidayumsg($phonenums,$params,$template){
        Vendor('Alidayu.TopSdk');
        $config=C('ALIDAYU_CONFIG');
        $c = new TopClient;
        $c->appkey = $config['appkey'];
        $c->secretKey = $config['secretKey'];
        $req = new AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend($config['extend']);
        $req->setSmsType($config['smsType']);
        $req->setSmsFreeSignName($config['smsFreeSignName']);
        $req->setSmsParam($params);
        $req->setRecNum($phonenums);
        $req->setSmsTemplateCode($template);
        $resp = $c->execute($req);
        return $resp;
    }

    //生成n位随机数
    function createRandomCode($n){
        $code = '';
        for ($i=0; $i < $n ; $i++) {
            $code .= rand(0,9);
        }
        return $code;
    }
    //手机号隐藏中间四位
    function phonenumHidden($phonenum){
        return substr_replace($phonenum,'****',3,4);
    }

    //姓名隐藏名
    function nameHidden($name){
        $strlen     = mb_strlen($name, 'utf-8');
        $firstStr     = mb_substr($name, 0, 1, 'utf-8');
        $lastStr     = mb_substr($name, -1, 1, 'utf-8');
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }

    //物流公司查询
    function expressList($expName,$maxSize,$page){
        $host = "http://ali-deliver.showapi.com";
        $path = "/showapi_expressList";
        $method = "GET";
        $aliapi = C(ALIAPI_CONFIG);
        $appcode = $aliapi['appcode'];
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "expName=".$expName."&maxSize=".$maxSize."&page=".$page;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $res = curl_exec($curl);
        return $res;
    }

    //物流订单查询
    function expressInfo($company,$number){
        $host = "http://ali-deliver.showapi.com";
        $path = "/showapi_expInfo";
        $method = "GET";
        $aliapi = C(ALIAPI_CONFIG);
        $appcode = $aliapi['appcode'];
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "com=".$company."&nu=".$number;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $res = curl_exec($curl);
        return $res;
    }

    //身份证识别
    function idAuth($image){
        $host = "http://idcard.aliapi.hanvon.com";
        $path = "/rt/ws/v1/ocr/idcard/cropped/recg";
        $method = "POST";
        $aliapi = C(ALIAPI_CONFIG);
        $appcode = $aliapi['appcode'];
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        array_push($headers, "Content-Type".":"."application/octet-stream");
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "code=56bc30ea-2229-4891-9c92-8a022f10889f";
        $bodys = "{\"uid\": \"".$_SERVER['SERVER_ADDR']."\",\"image\": \"".$image."\"}";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $res = curl_exec($curl);
        return $res;
    }

    function cut_str($sourcestr,$cutlength)
    {
       $returnstr='';
       $i=0;
       $n=0;
       $str_length=strlen($sourcestr);//字符串的字节数
       while (($n<$cutlength) and ($i<=$str_length))
       {
          $temp_str=substr($sourcestr,$i,1);
          $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
          if ($ascnum>=224)    //如果ASCII位高与224，
          {
    $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
             $i=$i+3;            //实际Byte计为3
             $n++;            //字串长度计1
          }
          elseif ($ascnum>=192) //如果ASCII位高与192，
          {
             $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
             $i=$i+2;            //实际Byte计为2
             $n++;            //字串长度计1
          }
          elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
          {
             $returnstr=$returnstr.substr($sourcestr,$i,1);
             $i=$i+1;            //实际的Byte数仍计1个
             $n++;            //但考虑整体美观，大写字母计成一个高位字符
          }
          else                //其他情况下，包括小写字母和半角标点符号，
          {
             $returnstr=$returnstr.substr($sourcestr,$i,1);
             $i=$i+1;            //实际的Byte数计1个
             $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
          }
       }
             if ($str_length>$i){
              $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
          }
        return $returnstr;
    }

    function getVod(){
        Vendor('Qcloudapi.Vod');
        $vod = new \Vod();
        return $vod;
    }

    /**
	* 验证手机号是否正确
	* @author honfei
	* @param number $mobile
	*/
	function isMobile($mobile) {
	    if (!is_numeric($mobile)) {
	        return false;
	    }
	    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
	}

    function get_client_ip1($type = 0) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($_SERVER['HTTP_X_REAL_IP']){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    function check_email($email){
        $email_preg =  '/^\w+@\w+(\.\w+)+$/';
        if(preg_match($email_preg,$email)){
            return true;
        }else{
            return false;
        }
    }

/**
 * @param $order_details需要处理的订单中的购物车详情字符串  5:20,6:10
 * @param $order_details需要处理的订单中的订单详情字符串  5:20:19.9,6:10:18.99
 * @type 1不带价格的 2带价格的
 */
function setGoodsDetailData($order_details,$type=1)
{
    if(empty($order_details)) return false;
    $arr = explode(',',$order_details);
    $goods_id_arr =  [];
    $data = [];
    if($type == 1){
        //购物车详情
        foreach ($arr as $val) {
            $array = explode(':',$val);
            $goods_id_arr[] = $array[0];
            $data[] = [
                'goods_id'=>$array[0],
                'goods_num'=>$array[1],
            ];
        }
    }else if($type == 2){
        //商品详情
        foreach ($arr as $val) {
            $array = explode(':',$val);
            $goods_id_arr[] = $array[0];
            $data[] = [
                'goods_id'=>$array[0],
                'goods_num'=>$array[1],
                'goods_buy_price'=>$array[2],
            ];
        }
    }
    return ['goods_id_arr'=>$goods_id_arr,'data'=>$data];
}